import 'dart:convert';

import 'package:example_example/bean/ToTaskBean.dart';
import 'package:example_example/services/ScreenAdapter.dart';
import 'package:example_example/util/HttpMethod.dart';

import '../../pages/view/LoadingView.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../../bean/BaseBean.dart';
import '../../global/Global.dart';
import '../../global/GlobalUrl.dart';
import '../../services/TLSizeFit.dart';
import '../../util/HttpUtil.dart';
import '../../util/LogUtil.dart';
import '../../util/ToastUtils.dart';
import '../../util/Storage.dart';
import '../view/ItemToDoTaskView.dart';
import '../../bean/order/AutogeneratedBean.dart';
import '../../pages/person/Login.dart';
import '../view/ItemFinishTaskView.dart';
import '../view/HeaderView.dart';
import '../view/NoDataView.dart';

/**刷新来自官网的demo
 * flutter_easyrefresh   刷新的第三方组件
 * https://pub.dev/packages/flutter_easyrefresh/example
 *
 * 办结任务
 *
 */

class FinishTaskPage extends StatefulWidget {
  FinishTaskPage({Key key}) : super(key: key);

  _FinishTaskPagePageState createState() => _FinishTaskPagePageState();
}

class _FinishTaskPagePageState extends State<FinishTaskPage> {
  EasyRefreshController _controller;

  // 条目总数
//  int _count = 6; //20

  List dataList = [];
  int pageIndex = 1;
  bool noDataflag = false;

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();

    initHttpData();
    HttpMethod.initDictionaryData(this.context);
  }

  @override
  Widget build(BuildContext context) {
    TLSizeFit.initialize();
    ScreenAdapter.init(context);

    return Scaffold(
//        appBar: AppBar(
//          title: Text("EasyRefresh"),
//        ),
      appBar: HeaderView(
        title: "办结任务",
        isShowReturnArrow: true,
      ),
      body: Stack(
        children: <Widget>[
          EasyRefresh.custom(
            enableControlFinishRefresh: false,
            // 是否开启控制结束刷新
            enableControlFinishLoad: true,
            // 是否开启控制结束加载
            controller: _controller,
            // EasyRefresh控制器
//          header: ClassicalHeader(),
            header: ClassicalHeader(
              enableInfiniteRefresh: false,
              refreshText: "拉动刷新",
              refreshReadyText: "释放刷新",
              refreshingText: "正在刷新...",
              refreshedText: "刷新完成",
              refreshFailedText: "刷新失败",
              noMoreText: "没有更多数据",
              showInfo: false, // 是否显示时间
//            infoText: "更新于 %T",
            ),
//          footer: ClassicalFooter(),
            footer: ClassicalFooter(
              loadText: "拉动加载",
              loadReadyText: "释放加载",
              loadingText: "正在加载...",
              loadedText: "加载完成",
              loadFailedText: "加载失败",
              noMoreText: "没有更多数据",
              infoText: "更新于 %T",
            ),
            onRefresh: () async {
              print('onRefresh');
              pageIndex = 1;
              initHttpData();
//          await Future.delayed(Duration(seconds: 2), () {
//
//          });
            },
            onLoad: () async {
              print('onLoad');
              pageIndex++;
              initHttpData();
//          await Future.delayed(Duration(seconds: 2), () {
//
////            _controller.finishLoad(noMore: _count >= 40);
//          });
            },
            slivers: <Widget>[
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    if (dataList != null && dataList.length > 0) {
                      return InkWell(
                        child: ItemFinishTaskView(dataList[index]),
                        onTap: () {
//                          String processInstanceId =
//                              dataList[index]["processInstanceId"];
//                          print("查看流程图processInstanceId:$processInstanceId");
//                          if (processInstanceId == null) {
//                            processInstanceId = "";
//                          }
//                          String url = GlobalUrl.WEB_CHART_URL +
//                              "?processInstanceId=" +
//                              processInstanceId +
//                              "&platform=app";
////                          String url = GlobalUrl.HELP;
//                          url="http://192.168.20.114:8181/#/app/flow-static?utcFormId=&utcFormType=1&platform=app&utcInterfaceUrl=/us-process/task/update&utcRoutePath=project/regular/change-apply/operation&utcTitle=%E9%A1%B9%E7%9B%AE%E4%BA%A4%E4%BB%98%E8%B4%B9%E7%94%A8%E5%8F%98%E6%9B%B4%E7%94%B3%E8%AF%B7-%E4%BA%8C%E7%BA%A7%E5%AE%A1%E6%A0%B8&utcType=3&name=%E9%A1%B9%E7%9B%AE%E4%BA%A4%E4%BB%98%E8%B4%B9%E7%94%A8%E5%8F%98%E6%9B%B4%E7%94%B3%E8%AF%B7-%E4%BA%8C%E7%BA%A7%E5%AE%A1%E6%A0%B8&id=8f88ac08-413a-11ec-bd0d-525400044e09&taskDefinitionKey=USER_TASK_PROJECT_COST_DELIVERY_AUDIT_2&processInstanceId=522a803f-4132-11ec-bd0d-525400044e09";
//
//                          Navigator.pushNamed(context, '/webViewUtilPage',
//                              // webViewUtilPage   WebViewExample
//                              arguments: {
//                                Global.WEBVIEW_TAG: Global.HIISTORYTASK,
//                                Global.WEBVIEW_URL: url,
//                              }).then((value) {
//                            //HELP
//                            print('webview:$value');
//                          });
                          setToDoNet(index);
                        },
                      );
//                  return ItemFinishTaskView(dataList[index]);
                    } else {
                      return
//                    Container(
//                    width: 60.0,
//                    height: 60.0,
//                    child: Center(
//                      child: Text('$index'),
//                    ),
//                    color:
//                    index % 2 == 0 ? Colors.grey[300] : Colors.transparent,
//                  );

                          Container(
                        height: TLSizeFit.screenHeight - TLSizeFit.setPx(200),
                        alignment: Alignment.center,
                        child: Center(
                          child: Text('还没有数据哦'),
                        ),
                        color: Colors.transparent,
                      );
                    }
                  },
//              childCount: dataList.length==0?1:dataList.length,
                  childCount: dataList.length,
                ),
              ),
            ],
          ),
          (this.dataList.length <= 0 && !noDataflag) ? LoadingView() : Container(),
          noDataflag ? NoDataView(): Container(),
        ],
      ),
    );
  }

  /**
   * 处理待办任务前先访问接口
   */
  setToDoNet(int index) async {
    //

    String taskDefinitionKey = dataList[index]["taskDefinitionKey"];
    var itemBean = dataList[index];
    if (taskDefinitionKey == null || taskDefinitionKey == "") {
      return;
    }
    String apiUrlhttp = GlobalUrl.UPUSERTASKCONFIG;

    var map = {
      "code": taskDefinitionKey,
    };

    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
//    LogUtil.v("获取的access_token：$access_token");

    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.get(apiUrlhttp, data: map, headers: mapHeaders, success: (data) {
      Navigator.of(context).pop();

//      接口的数据：{code: 200, success: true, data: {
//      id: 1400018369129914369,
//      utcTitle: 售前立项一级审核,
//      utcType: 1,
//      utcRoutePath: project/prepare/approve,
//      utcFormType: 1,
//      utcFormId: null,
//      utcInterfaceUrl: /us-
//      process/task/auditOne},
//      msg: 操作成功}

      String str = json.encode(data);
      LogUtil.v("接口的数据22:$str");

      var toTaskBean = ToTaskBean.fromJson(data);

      var success = toTaskBean.success;
      if (success != null && success) {
        print("...是否进来了呀");

        var taskBean = toTaskBean.data;
//
        String utcFormId = taskBean.utcFormId;
        String utcFormType = taskBean.utcFormType;
        String utcInterfaceUrl = taskBean.utcInterfaceUrl;
        String utcRoutePath = taskBean.utcRoutePath;
        String utcTitle = taskBean.utcTitle;
        String utcType = taskBean.utcType;

        if (utcFormId == null) {
          utcFormId = "";
        }
        if (utcFormType == null) {
          utcFormType = "";
        }
        if (utcInterfaceUrl == null) {
          utcInterfaceUrl = "";
        }
        if (utcRoutePath == null) {
          utcRoutePath = "";
        }
        if (utcTitle == null) {
          utcTitle = "";

        }
        if (utcType == null) {
          utcType = "";
        }
        utcTitle = Uri.encodeComponent(utcTitle);
        print("utcFormId:$utcFormId");
        print("utcFormType:$utcFormType");

        // 注意拼接的参数不能有null，否则会报错
//        String url = GlobalUrl.WEB_TODOTASK_URL + "?utcFormType="+utcFormType;

//        print("...拼接的url:"+url);
        String variableJsonStr = json.encode(itemBean["variableJson"]);

        String url = "";
        if (utcFormType == "1") {
          url = GlobalUrl.WEB_STATIC_URL;
        } else if(utcFormType == "2"){
          url = GlobalUrl.WEB_DYNAMIC_URL;
        } else {
          url = GlobalUrl.WEB_CUSTOM_URL;
        }

//        var pathURL ="?utcFormId="+utcFormId+"&utcFormType="+utcFormType+"&platform=app"+"&utcInterfaceUrl="+utcInterfaceUrl
//            +"&utcRoutePath="+utcRoutePath+"&utcTitle="+utcTitle+"&utcType="+utcType+"&name="+utcTitle+"&id="+itemBean["id"]+
//            "&taskDefinitionKey="+taskDefinitionKey+"&processInstanceId="
//            +itemBean["processInstanceId"];

        url = url +
            "?utcFormId=" +
            utcFormId +
            "&utcFormType=" +
            utcFormType +
            "&platform=app" +
            "&utcInterfaceUrl=" +
            utcInterfaceUrl +
            "&utcRoutePath=" +
            utcRoutePath +
            "&utcTitle=" +
            utcTitle +
            "&utcType=" +
            utcType +
            "&name=" +
            utcTitle +
            "&id=" +
            itemBean["id"] +
            "&taskDefinitionKey=" +
            taskDefinitionKey +
            "&processInstanceId=" +
            itemBean["processInstanceId"];

//        url = url+"?"+Uri.encodeComponent(pathUrl);

//       url = url + json.encode(pathURL);
//          url = json.encode(url+pathURL);
//           +"&variableJson="+variableJsonStr;

//        ToastUtils.toast(url);

        Navigator.pushNamed(context, '/webViewUtilPage', //WebViewExample
            arguments: {
              Global.WEBVIEW_TAG: Global.HIISTORYTASK,
              Global.WEBVIEW_URL: url,

              "id": dataList[index]["id"],
//                            "count":count++,
              'variableJsonStr': variableJsonStr,
            }).then((value) {
          print('webview:$value');
        });
      } else {}
    }, error: (errorMsg) {
      print("//....error了啊");
      Navigator.of(context).pop();
    });
  }

  initHttpData() async {
//    http://10.66.1.100:8181/api/us-process/process/pageFinished?current=1&size=10

    String apiUrlhttp = GlobalUrl.FinishedFINISHED;
    var map = {
      "current": pageIndex,
      "size": "10",
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    HttpUtil.get(apiUrlhttp, data: map, headers: mapHeaders, success: (data) {
      // 下拉刷新停止
      _controller.resetLoadState();
      //  上拉加载停止
      _controller.finishLoadCallBack();
//    _controller.finishLoad(noMore: false);
      _controller.finishLoad();

      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
//      LogUtil.v("body:$body");
      if (success != null && success == true) {
        LogUtil.v("进来了");
        List getList = body["records"];
//        LogUtil.v("getList:$getList");
        LogUtil.v("获取的接口数据：${getList.length}");

        if (pageIndex == 1) {
          dataList.clear();
          dataList.addAll(getList);
        } else {
          dataList.addAll(getList);
        }
        print(dataList.length);

        if (dataList.length == 0) {
          setState(() {
            noDataflag = true;
          });
        } else {
          setState(() {
            dataList = dataList;
            noDataflag = false;
          });
        }

//        for (var i = 0; i < getList.length; i++) {
//          var ppProjectName = getList[i]["ppProjectName"];
//          LogUtil.v("ppProjectName:$ppProjectName");
//          var variableJson = getList[i]['variableJson'];
////          LogUtil.v("variableJson:$variableJson");
//          variableJson = json.decode(variableJson);
//          var biProjectName = variableJson["biProjectName"];
//          LogUtil.v("biProjectName:$biProjectName");
//        }
      } else {
        if (message != null) {
          ToastUtils.toast(message);
        }
        if (code == "401") {
          //用户登录超时
          print("超时了啊");
          Storage.clear(); // 清除数据
          //跳转并关闭当前页面
          Navigator.pushAndRemoveUntil(
            context,
            new MaterialPageRoute(builder: (context) => new LoginPage()),
            (route) => route == null,
          );
        }
      }
    }, error: (errorMsg) {
      print("待办任务..办结任务..errorMsg: $errorMsg");
      // 下拉刷新停止
      _controller.resetLoadState();

      //  上拉加载停止
      _controller.finishLoadCallBack();
//            _controller.finishLoad(noMore: false);
      _controller.finishLoad();
    });
  }
}
